import SocketServer
import sys
import G
import socket
import threading

class MyTcpHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        clientaddr=()
        clientaddr=self.request.getsockname()



        
        #boolExist=False
        #for ipaddr,port in G.CLST:
        #    if ipaddr==clientaddr[0]:
        #        boolExist=True
        #if boolExist==False:
        #    G.CLST.append(clientaddr)
        #    print "append:"+clientaddr[0]

        #boolExist=False

        
        self.data=self.request.recv(10240).strip()
        
        print "Request from client:{}".format(self.data.strip())

        G.SMSG+=self.data+"\r\n"
        
        #self.request.sendall("Send From Server:{}".format(G.SMSG))

        #self.request.sendall(G.SMSG)
        
        for ipaddr,port in G.CLST:
            print "go in "+ipaddr
            t=threading.Thread(target=self.sendMsg,args=(ipaddr,self.data.strip()))
            t.daemon=False
            t.start()
            #host,port=(ipaddr,10000)
            #client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            #client.connect((host,port))
            #client.sendall(self.data)
            #client.close()
            
    def sendMsg(self,ipaddr,data):
        host,port=(ipaddr,10000)
        client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        client.connect((host,port))
        client.sendall(data)
        client.close()
            
if __name__=="__main__":
    print("Server Start")
    G.CLST.append(("192.168.0.185",10000))
    G.CLST.append(("192.168.0.72",10000))    
    G.CLST.append(("192.168.0.101",10000))
    G.CLST.append(("192.168.0.95",10000))
    G.CLST.append(("192.168.0.87",10000))
    G.CLST.append(("192.168.0.70",10000))
    G.CLST.append(("192.168.0.130",10000))
    G.CLST.append(("192.168.0.75",10000))
    G.CLST.append(("192.168.0.168",10000))
    objServer=SocketServer.TCPServer(("192.168.0.185",9999),MyTcpHandler)
    objServer.serve_forever()
